package com.xyxy.platform.modules.service.content.impl;

import com.xyxy.platform.modules.core.cache.memcached.SpyMemcachedClient;
import com.xyxy.platform.modules.entity.content.Article;
import com.xyxy.platform.modules.repository.mybatis.content.ArticleCatMapper;
import com.xyxy.platform.modules.repository.mybatis.content.ArticleMapper;
import com.xyxy.platform.modules.service.content.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * ArticleServiceImpl
 * 文章 服务
 * 加入缓存
 *
 * @author yangdianjun
 * @updator caizhengda
 * @date 2016/1/12 0012
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private SpyMemcachedClient memcachedClient;

    @Override
    public Article insertArticle(Article article) {
        int i = articleMapper.insertSelective(article);
        memcachedClient.set(this.getCacheKey(article.getArticleId()), 60 * 60 * 24, article);
        return i > 0 ? article : null;
    }

    @Override
    public Article selectById(Long articleId) {
        if (null == articleId) return null;
        Article article = memcachedClient.get(this.getCacheKey(articleId));
        if (null == article) {
            article = articleMapper.selectByPrimaryKey(articleId);
        }
        return article;
    }

    @Override
    public Article update(Article article) {
        int rows = articleMapper.updateByPrimaryKeySelective(article);
        if (rows > 0) {
            memcachedClient.set(this.getCacheKey(article.getArticleId()), 60 * 60 * 24, article);
            return article;
        }
        return null;
    }

    private String getCacheKey(Long articleId) {
        return Article.class.toString() + articleId;
    }
}
